﻿using BaseData.Exts;
using BaseData.Models;
using BaseLib.Helper;
using BaseUtility;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace WebUI.Ashx.Acc.Staff
{
    /// <summary>
    /// NewsAdminInfoList 的摘要说明
    /// </summary>
    public class NewsAdminInfoList : Base, IHttpHandler
    {
        private readonly AccClass _accId = new AccExts(new GetAccType().Parse(Request.QueryString["url"])).Instances;
        public void ProcessRequest(HttpContext context)
        {
            if (_accId.Id == 0 || string.IsNullOrWhiteSpace(_accId.Name) || _accId.Type == 0) return;
            var pn = context.Request.Form["page"].ToInt(1);
            var ps = context.Request.Form["rows"].ToInt(10);
            var fl = context.Request.QueryString["file"].ToNull();
            using (var ctx = new ContextExt())
            {
                var takeInfo = new string[] { "PkId", "NodeId", "Title", "TitleSe", "FlagPass", "FlagStatus", "DateTimeCreate", };
                var takeNode = new string[] { "Title", };
                var skipResx = new string[] { "PkId", "NodeId", "InfoId", "Type", };
                var list = new List<DataTableClass.Convert>
                {
                    new DataTableClass.Convert() { Assembly = new Web_Base_News_Info().TToAssembly(), take = takeInfo, },
                    new DataTableClass.Convert() { Assembly = new Web_Base_News_Node().TToAssembly(), take = takeNode, fix = "Node", },
                    new DataTableClass.Convert() { Assembly = new Web_Base_Exts_Resx().TToAssembly(), skip = skipResx, },
                };
                var dtNew = list.IListConvertToDataTable(); dtNew.Clear();

                var infoz = ctx.Web_Base_News_Info.Select(q => q);
                var resxz = ctx.Web_Base_Exts_Resx.Select(q => q);

                if (fl.Compare("image")) infoz = infoz.Where(w => resxz.Where(res => res.ImagesCount > 0).Select(res => res.InfoId).Contains(w.PkId));
                if (fl.Compare("media")) infoz = infoz.Where(w => resxz.Where(res => res.MediaCount > 0).Select(res => res.InfoId).Contains(w.PkId));
                if (fl.Compare("banner")) infoz = infoz.Where(w => resxz.Where(res => res.BannersCount > 0).Select(res => res.InfoId).Contains(w.PkId));
                var reqId = context.Request.QueryString["id"].ToInt(0);
                var lowers = new List<int>();
                if (reqId != 0)
                {
                    lowers = this.GetLowers(ctx, new List<int> { reqId });
                    if (lowers.Any()) infoz = infoz.Where(w => lowers.Contains(w.NodeId.Value));
                }
                // id为空 且 非叶节点(=1，代表自身节点)，以SortId排序
                if (reqId != 0 && !lowers.Any())
                    infoz = infoz.OrderByDescending(o => o.SortId);
                else
                    infoz = infoz.OrderByDescending(o => o.DateTimeCreate).ThenByDescending(o => o.DateTimeOnline).ThenByDescending(o => o.PkId);
                // 总数
                var count = infoz.Count();
                var infoList = infoz.Skip(((pn > 0 ? pn : 1) - 1) * ps).Take(ps).ToList();
                // 1.Info存入DataTable。
                dtNew = infoList.IListFillDataRow(new DataTableClass.Fills { table = dtNew, take = takeInfo, });
                // 2.Resx存入DataTable。
                var infoid = infoList.Select(s => s.PkId);
                var resx = resxz.Where(w => infoid.Contains(w.InfoId ?? 0));
                const string imgsrc = "<img src=\"/Ashx/App/MakeImage.ashx?method=x&w=30&h=22&q=100&f={0}\" style=\"height:22px;\" alt=\"\" />"; ;
                foreach (var res in resx)
                {
                    res.Image = !string.IsNullOrEmpty(res.Image) ? string.Format(imgsrc, res.Image) : "";
                    res.Guide = !string.IsNullOrEmpty(res.Guide) ? string.Format(imgsrc, res.Guide) : "";
                    res.Banner = !string.IsNullOrEmpty(res.Banner) ? string.Format(imgsrc, res.Banner) : "";
                    res.Icon = !string.IsNullOrEmpty(res.Icon) ? string.Format(imgsrc, res.Icon) : "";
                    res.IListFillDataRow(new DataTableClass.Fill { table = dtNew, skip = skipResx, key = "PkId", value = res.InfoId ?? 0, });
                }
                // 3.Node存入DataTable。
                var nodez = ctx.Web_Base_News_Node.Select(q => q);
                var nodeid = infoList.Select(s => s.NodeId).Distinct();
                nodez = nodez.Where(w => nodeid.Contains(w.PkId));
                foreach (var node in nodez) node.IListFillDataRow(new DataTableClass.Fill { table = dtNew, take = takeNode, fix = "Node", key = "NodeId", value = node.PkId, });
                // 4.Ezui存入DataTable。
                context.Response.Write(new Exts_EzUI() { total = count, rows = dtNew, info = fl + ":", }.ObjectsToJson());
            }
            context.Response.ContentType = "text/plain";
        }
        private List<int> GetLowers(ContextExt ctx, List<int> ids)
        {
            var items = this.GetLower(ctx, ids);
            if (items.Any()) ids.AddRange(this.GetLowers(ctx, items.ToList()));
            return ids;
        }
        private List<int> GetLower(ContextExt ctx, List<int> ids)
        {
            var items = from q in ctx.Web_Base_News_Node where ids.Contains(q.ParentId ?? 0) select q.PkId;
            return items.Any() ? items.ToList() : new List<int>();
        }
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}